package cn.zhang.reimbursement_1.config;
import cn.zhang.reimbursement_1.request.LoginRequest;
import cn.zhang.reimbursement_1.tools.CommonUtil;
import cn.zhang.reimbursement_1.tools.JWTUtil;
import cn.zhang.reimbursement_1.tools.JsonData;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 验证和解析token并吧用户信息保存到threadlocal
 */
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    public static ThreadLocal<LoginRequest> loginThreadLocal = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取token
        String token = request.getHeader("token");
        if (StringUtils.isBlank(token)){
            token = request.getParameter("token");
        }else {
            //验证token
            Claims claims = JWTUtil.checkJWT(token);
            //验证结果为空的话，则token过期告知用户重新获取
            if(claims==null){
                CommonUtil.sendJsonMessage(response, JsonData.buildCodeAndMsg(-1,"账号过期，请重新登录"));
                return false;
            }

            //解析token
            Integer id  = Integer.valueOf(claims.get("id").toString());
            String name = String.valueOf(claims.get("name"));
            String role = String.valueOf(claims.get("role"));

            LoginRequest loginRequest = new LoginRequest();
            loginRequest.setId(id);
            loginRequest.setUsername(name);
            loginRequest.setRolename(role);

            loginThreadLocal.set(loginRequest);
            return true;

        }
        CommonUtil.sendJsonMessage(response, JsonData.buildCodeAndMsg(-1,"账号过期，请重新登录"));
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
